<?php
/**
 * Base model for other models.
 *
 * @category PhpCilux
 * @package  PhpCilux
 */

/**
 * Base model.
 *
 * @package PhpCilux
 */
class Model_Base
{

    /**
     * Constructor.
     *
     * @param array $options Several options (key -> value).
     */
    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

    /**
     * Magic setter.
     *
     * @param mixed $name  The property name.
     * @param mixed $value The property value.
     *
     * @return void
     * @throws Exception Invalid property.
     */
    public function __set($name, $value)
    {
        $method = 'set' . $name;
        if (!method_exists($this, $method)) {
            throw new Exception('Invalid property');
        }

        $this->$method($value);
    }

    /**
     * Magic getter.
     *
     * @param mixed $name The property name.
     *
     * @return mixed The value.
     * @throws Exception Invalid property.
     */
    public function __get($name)
    {
        $method = 'get' . $name;
        if (!method_exists($this, $method)) {
            throw new Exception('Invalid property');
        }

        return $this->$method();
    }

    /**
     * Set several options.
     *
     * @param array $options Several options (key -> value).
     *
     * @return Model_Base
     */
    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach ($options as $key => $value) {
            $method = 'set' . (str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }

        return $this;
    }

}